package com.spring.cloud.exception;

import com.spring.cloud.module.common.core.JsonResponse;
import com.spring.cloud.module.common.exception.BaseExcepiton;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LogManager.getLogger(GlobalExceptionHandler.class);

    public static final String DEFAULT_ERROR_VIEW = "error";

    @ExceptionHandler(value = Exception.class)
    public ModelAndView defaultErrorHandler(HttpServletRequest request, Exception ex) throws Exception {
        logger.error(">>>Exception={}", ex);
        ModelAndView mav = new ModelAndView();
        mav.addObject("exception", ex);
        mav.addObject("url", request.getRequestURL());
        mav.setViewName(DEFAULT_ERROR_VIEW);
        return mav;
    }


    @ExceptionHandler(value = BaseExcepiton.class)
    @ResponseBody
    public JsonResponse JsonErrorHandler(HttpServletRequest request, BaseExcepiton ex) throws Exception {
        logger.error(">>>Exception={}", ex);
        JsonResponse jsonResponse = new JsonResponse();
        jsonResponse.setError(ex.getMessage());
        jsonResponse.setStatus(ex.getCode());
        return jsonResponse;
    }
}
